package com.common.tool;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.entity.weixin.TextMessage;
import com.entity.weixin.UnifiedOrder;
import com.entity.weixin.WeiXinUserInfo;
import com.jfinal.kit.PropKit;
import com.thoughtworks.xstream.XStream;

public class WeiXinUtil {

    public static boolean checkSignature(String signature, String timestamp, String nonce, String echostr)
	    throws NoSuchAlgorithmException {

	String[] arr = new String[] { PropKit.get("weixin_token"), timestamp, nonce };
	Arrays.sort(arr);

	StringBuilder content = new StringBuilder();
	for (int i = 0; i < arr.length; i++) {
	    content.append(arr[i]);
	}
	String tmp = getSha1(content.toString());
	if (tmp.toString().equals(signature)) {
	    return true;
	} else {
	    return false;
	}

    }

    public static String getSha1(String str) {
	if (str == null || str.length() == 0) {
	    return null;
	}
	char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	try {
	    MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
	    mdTemp.update(str.getBytes("UTF-8"));

	    byte[] md = mdTemp.digest();
	    int j = md.length;
	    char buf[] = new char[j * 2];
	    int k = 0;
	    for (int i = 0; i < j; i++) {
		byte byte0 = md[i];
		buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
		buf[k++] = hexDigits[byte0 & 0xf];
	    }
	    return new String(buf);
	} catch (Exception e) {
	    return null;
	}
    }

    public static Map<String, String> xmlToMap(HttpServletRequest req) throws IOException, DocumentException {
	Map<String, String> map = new HashMap<String, String>();
	SAXReader reader = new SAXReader();

	InputStream ins = req.getInputStream();
	Document doc = reader.read(ins);

	Element root = doc.getRootElement();
	List<Element> list = root.elements();
	for (Element e : list) {
	    map.put(e.getName(), e.getText());
	}
	ins.close();
	return map;
    }
 

    public static String textMessageToXml(TextMessage textMessage) {
	XStream xstream = new XStream();
	xstream.alias("xml", TextMessage.class);
	return xstream.toXML(textMessage);
    }
    
    public static String unifiedOrderToXml(UnifiedOrder order) {
   	XStream xstream = new XStream();
   	xstream.alias("xml", UnifiedOrder.class);
   	return xstream.toXML(order);
       } 

    public static Map<String, Object> getMapFromJson(String jsonStr) {
	Map<String, Object> map = new HashMap<String, Object>();
	map = JSON.parseObject(jsonStr, new TypeReference<Map<String, Object>>() {
	});

	return map;
    }

    /**
     * 得到微信公共接口调用凭证access_token
     * 
     * @return
     */
    public static String getAccessToken() {
	String url = "https://api.weixin.qq.com/cgi-bin/token";
//	StringBuilder sb = new StringBuilder().append("grant_type=client_credential&").append("&appid=")
//		.append("wxf48b8f9f612266bc").append("&secret=").append("5b70ef77a689fa38647bb842e4a44b07");
	
	
	
	StringBuilder sb = new StringBuilder().append("grant_type=client_credential").append("&appid=")
//		.append("wxc294b2b55c28f7d6").append("&secret=").append("ea9cfc4c480d1e0c90424d85d06ed82b");
//debug		.append("wxf48b8f9f612266bc").append("&secret=").append("5b70ef77a689fa38647bb842e4a44b07");
		.append("wx4a2775ee91047dc9").append("&secret=").append("afe3fbcfc9088eb2aae399832b1fe1f3");	
//	 .append(PropKit.get("appid")).append("&secret=").append(PropKit.get("secret"));
	
		
		
//	grant_type=client_credential&appid=wx4a2775ee91047dc9&secret=5b70ef77a689fa38647bb842e4a44b07
	System.out.println(sb.toString());
	String s = HttpRequest.sendGet(url, sb.toString());
	System.out.println("getAccessToken=" + s);
	Map<String, Object> map = WeiXinUtil.getMapFromJson(s);
	return map.get("access_token").toString();
    }

    public String getTicketForCreateOwerCard(String accessToken, String openid) throws UnsupportedEncodingException {
	System.out.println("createOwerCard");
	JSONObject json = new JSONObject();
	String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
	Map map = new HashMap();
	Map mapscene = new HashMap();
	map.put("scene_str", openid);
	mapscene.put("scene", map);
	json.put("expire_seconds", 604800);
	json.put("action_name", "QR_LIMIT_STR_SCENE");
	json.put("action_info", mapscene);

	System.out.println(json.toJSONString());
	String s = HttpRequest.senPost(url, json);
	System.out.println(s);
	Map relMap = WeiXinUtil.getMapFromJson(s);

	String ticket = relMap.get("ticket").toString();
	System.out.println(ticket);
	return ticket;
    }

    public String makeTextCustomMessage(String openId, String content) {
	content.replace("\"", "\\\"");
	String jsonMsg = "{\"touser\":\"%s\",\"msgtype\":\"text\",\"text\":{\"content\":\"%s\"}}";
	return String.format(jsonMsg, openId, content);
    }

    /**
     * 组装图片客服消息
     * 
     * @param openId
     *            消息发送对象
     * @param mediaId
     *            媒体文件id
     * @return
     */
    public String makeImageCustomMessage(String openId, String mediaId) {
	String jsonMsg = "{\"touser\":\"%s\",\"msgtype\":\"image\",\"image\":{\"media_id\":\"%s\"}}";
	return String.format(jsonMsg, openId, mediaId);
    }

    /**
     * 组装语音客服消息
     * 
     * @param openId
     *            消息发送对象
     * @param mediaId
     *            媒体文件id
     * @return
     */
    public String makeVoiceCustomMessage(String openId, String mediaId) {
	String jsonMsg = "{\"touser\":\"%s\",\"msgtype\":\"voice\",\"voice\":{\"media_id\":\"%s\"}}";
	return String.format(jsonMsg, openId, mediaId);
    }

    /**
     * 组装视频客服消息
     * 
     * @param openId
     *            消息发送对象
     * @param mediaId
     *            媒体文件id
     * @param thumbMediaId
     *            视频消息缩略图的媒体id
     * @return
     */
    public String makeVideoCustomMessage(String openId, String mediaId, String thumbMediaId) {
	String jsonMsg = "{\"touser\":\"%s\",\"msgtype\":\"video\",\"video\":{\"media_id\":\"%s\",\"thumb_media_id\":\"%s\"}}";
	return String.format(jsonMsg, openId, mediaId, thumbMediaId);
    }

    /**
     * 组装音乐客服消息
     * 
     * @param openId
     *            消息发送对象
     * @param music
     *            音乐对象
     * @return
     */
    // public static String makeMusicCustomMessage(String openId, Music music) {
    // String jsonMsg =
    // "{\"touser\":\"%s\",\"msgtype\":\"music\",\"music\":%s}";
    // jsonMsg = String.format(jsonMsg, openId,
    // JSONObject.fromObject(music).toString());
    // // 参数名称替换 @20140125
    // jsonMsg = jsonMsg.replace("musicUrl", "musicurl");
    // jsonMsg = jsonMsg.replace("HQMusicUrl", "hqmusicurl");
    // jsonMsg = jsonMsg.replace("thumbMediaId", "thumb_media_id");
    // return jsonMsg;
    // }

    /**
     * 组装图文客服消息
     * 
     * @param openId
     *            消息发送对象
     * @param articleList
     *            图文消息列表
     * @return
     */
    // public static String makeNewsCustomMessage(String openId, List<Article>
    // articleList) {
    // String jsonMsg =
    // "{\"touser\":\"%s\",\"msgtype\":\"news\",\"news\":{\"articles\":%s}}";
    // jsonMsg = String.format(jsonMsg, openId,
    // JSONArray.fromObject(articleList).toString().replaceAll("\"", "\\\""));
    // // 将jsonMsg中的picUrl替换为picurl
    // jsonMsg = jsonMsg.replace("picUrl", "picurl");
    // return jsonMsg;
    // }

    public boolean sendCustomMessage(String jsonMsg) {
	boolean flag = false;
	String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN";
	requestUrl = requestUrl.replace("ACCESS_TOKEN", this.getAccessToken());
	String s = HttpRequest.sendPost(requestUrl, jsonMsg);
	System.out.println(s);
	return flag;
    }
    
    public void weixinSendMemberReqMessge(String userName,String reqopenId) {
   	String openId="otFedvw6QnZPsLI2RqVg25nmW5sw";
   	//TODO:确认页面；
   	String text = "<a href="+PropKit.get("weixin_area")+"/weixin/members?reqopenId='+reqopenId+'>"+userName+"申请成为商家！请您确认</a>";
   	String content = makeTextCustomMessage(openId, text);
   	sendCustomMessage(content);
       }
    // 得到用户信息
    public WeiXinUserInfo getUserInfo(String openid) {
	String url = "https://api.weixin.qq.com/cgi-bin/user/info";
	StringBuilder sb = new StringBuilder().append("access_token=").append(this.getAccessToken()).append("&openid=")
		.append(openid);
	String s = HttpRequest.sendGet(url, sb.toString());
	System.out.println(s);
//	"subscribe":1,"openid":"otFedvw6QnZPsLI2RqVg25nmW5sw","nickname":"缪缪","sex":2,"language":"zh_CN","city":"扬州","province":"江苏","country":"中国","headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/PiajxSqBRaEKUicgjiaEiaqGBTSYpBPS6uBibtxX3MgmsvIxOFAFmPNibiciaj4x1AtrmNg77OVoSS0JeEdxow1Xv38SYg\/0","subscribe_time":1491751196,"remark":"","groupid":0,"tagid_list":[]
	WeiXinUserInfo userInfo = JSON.parseObject(s, WeiXinUserInfo.class);
	System.out.println(userInfo.getCity());
	System.out.println(userInfo.getHeadimgurl());
	return userInfo;
    }
    
    
   
}
